#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
安装和设置脚本
"""

import os
import subprocess
import sys
import platform

def print_banner():
    """打印欢迎横幅"""
    banner = """
╔══════════════════════════════════════════════════╗
║           Telegram 消息监听工具                    ║
║              快速启动向导                          ║
╚══════════════════════════════════════════════════╝
"""
    print(banner)

def check_python_version():
    """检查Python版本"""
    version = sys.version_info
    if(version.major < 3 or (version.major == 3 and version.minor < 7)):
        print(f"❌ Python版本过低: {version.major}.{version.minor}")
        print("需要Python 3.7或更高版本")
        return False
    print(f"✅ Python版本: {version.major}.{version.minor}.{version.micro}")
    return True

def create_virtual_enviroment():
    """创建虚拟环境"""
    venv_name = "build_env"

    if os.path.exists(venv_name):
        print(f"⚠️  虚拟环境 '{venv_name}' 已存在")
        choice = input("是否要重新创建？(y/n): ").lower()
        if choice != 'y':
            return venv_name
        
        # 删除现存虚拟环境
        import shutil
        shutil.rmtree(venv_name)
        print(f"🗑️  已删除旧的虚拟环境")
    
    try: 
        print(f"🔧 正在创建虚拟环境 '{venv_name}'...")
        subprocess.check_call([sys.executable, "-m", "venv", venv_name])
        print(f"✅ 虚拟环境 '{venv_name}' 创建成功！")
        return venv_name
    except subprocess.CalledProcessError as e:
        print(f"❌ 创建虚拟环境失败: {e}")
        return None

def install_requirements_in_venv(venv_name):
        """在虚拟环境中安装依赖"""
        system = platform.system()

        if system == "Windows":
            python_path = os.path.join(venv_name, "Scripts", "python.exe")
            pip_path = os.path.join(venv_name, "Scripts", "pip.exe")
        else:
            python_path = os.path.join(venv_name, "bin", "python")
            pip_path = os.path.join(venv_name, "bin", "pip")

        if not os.path.exists(python_path):
            print(f"❌ 虚拟环境Python解释器不存在: {python_path}")
            return False

        try:
            print("📦 正在虚拟环境中安装依赖包...")
            subprocess.check_call([pip_path, "install", "--upgrade", "pip"])
            subprocess.check_call([pip_path, "install", "-r", "requirements.txt"])
            print("✅ 依赖包安装成功！")
            return True
        except subprocess.CalledProcessError as e:
            print(f"❌ 安装依赖包失败: {e}")
            return False

def create_run_script(venv_name):
    """创建在快速启动虚拟环境的脚本"""
    system = platform.system()

    if system == "Windows":
        python_path = f"{venv_name}\\Scripts\\python.exe"
        run_script = f"""@echo off
                        echo 🔍 检查虚拟环境...
                        if not exist "{python_path}" (
                            echo ❌ 虚拟环境不存在，请先运行 python create_venv.py
                            pause
                            exit /b 1
                        )

                        echo ✅ 使用虚拟环境运行程序
                        "{python_path}" main.py
                        pause
                    """
        with open("quick_run_venv.bat", "w", encoding="utf-8") as f:
            f.write(run_script)
        print("✅ 已创建一键激活虚拟环境脚本")

    else:
        python_path = f"{venv_name}/bin/python"
        run_script_unix = f"""#!/bin/bash
                            echo "🔍 检查虚拟环境..."
                            if [ ! -f "{python_path}" ]; then
                                echo "❌ 虚拟环境不存在，请先运行 python3 create_venv.py"
                                exit 1
                            fi

                            echo "✅ 使用虚拟环境运行程序"
                            "{python_path}" main.py
                            """
        with open ("quick_run_venv.sh", "w", encoding="utf-8") as f:
            f.write(run_script_unix)
        
        if system != "Windows":
            os.chmod("quick_run_venv.sh", 0o755)
        
        print("✅ 已创建一键激活虚拟环境脚本")

def check_env():
    """检查环境配置"""
    if not os.path.exists(".env"):
        if os.path.exists("env_example.txt"):
            print("📖 创建环境配置文件...")
            import shutil
            shutil.copy("env_example.txt", ".env")
            print("✅ 已创建 .env 文件")
        else:
            print("❌ 未找到环境配置模板")
            return False
    else:
        print("✅ 环境配置文件已存在")

    # 检查基本配置
    try:
        from config import API_ID, API_HASH
        if API_ID == 0 or API_HASH == "":
            print("❌ 请在 .env 文件中填入正确的 API_ID 和 API_HASH")
            return False
    except ImportError:
        print("❌ 配置文件导入失败☹️")
        return False
    
    return True

def print_usage_instructions(venv_name):
    """打印使用说明"""
    system = platform.system()
    
    print("\n" + "="*60)
    print("🎉 虚拟环境创建完成！")
    print("="*60)
    
    print(f"\n📁 虚拟环境位置: {os.path.abspath(venv_name)}")
    
    print("\n📋 使用方法:")
    
    if system == "Windows":
        print("  方法1 - 直接运行:")
        print("    quick_run_venv.bat")
        print("\n  方法2 - 手动激活:")
        print("    quick_run_venv.bat")
        print("    然后运行: python main.py")
        print("\n  方法3 - 命令行激活:")
        print(f"    {venv_name}\\Scripts\\activate")
    else:
        print("  方法1 - 直接运行:")
        print("    ./quick_run_venv.sh")
        print("\n  方法2 - 手动激活:")
        print("    ./quick_run_venv.sh")
        print("    然后运行: python main.py")
        print("\n  方法3 - 命令行激活:")
        print(f"    source {venv_name}/bin/activate")
    
    print("\n💡 提示:")
    print("  - 激活虚拟环境后，命令行前缀会显示环境名称")
    print("  - 运行 'deactivate' 命令可以退出虚拟环境")
    print("  - 虚拟环境只需要创建一次，之后直接激活使用即可")

def main():
    """主函数"""
    print_banner()
    print("🐍 Python虚拟环境创建工具")
    print("=" * 40)
    # 1.检查python版本
    if not check_python_version():
        sys.exit(1)
    
    # 2.创建虚拟环境，获取虚拟环境名称
    venv_name = create_virtual_enviroment()
    if not venv_name:
        sys.exit(1)
    
    # 3.虚拟环境中安装依赖
    if not install_requirements_in_venv(venv_name):
        sys.exit(1)

    # 4.创建一键激活脚本
    create_run_script(venv_name)

    # 打印使用说明
    print_usage_instructions(venv_name)

    """环境检查"""
    print("🔍 检查环境配置...")
    print("=" * 50)

    if not check_env():
        print("\n📋 配置步骤:")
        print("1. 复制 env_example.txt 为 .env")
        print("2. 访问 https://my.telegram.org/ 获取 API 凭据")
        print("3. 编辑 .env 文件，填入您的 API_ID 和 API_HASH")
        print("4. 重新运行此脚本")
        sys.exit(1)

    print("✅ 环境配置检查通过")
    print("🚀 启动 Telegram 监听器...")

    # try:
    #     import main
    # except Exception as e:
    #     print(f"❌ 启动失败：{e}")
    #     sys.exit(1)


if __name__ == "__main__":
    main()